package juc.popular;

import java.util.concurrent.TimeUnit;

/**
 * 死锁的模拟代码
 *
 * @author 王霄
 * @date 2022/1/30 13:04
 */
public class DeadLock {

    public static void main(String[] args) {
        Object resourceA = new Object();
        Object resourceB = new Object();

        new Thread(() -> {
            synchronized (resourceA) {
                sleep();
                System.out.println("线程1等待resourceB释放中...");
                synchronized (resourceB) {
                    System.out.println("线程1执行结束");
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (resourceB) {
                sleep();
                System.out.println("线程2等待resourceA释放中...");
                synchronized (resourceA) {
                    System.out.println("线程2执行结束");
                }
            }
        }).start();
    }

    private static void sleep() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
